#include "config.h"
#include <fstream>
#ifdef _WIN32
	#define WIN32_LEAN_AND_MEAN
	#include <windows.h>
#else
	#include <sys/stat.h>
#endif

using namespace std;

// Constructor
int ConfigClass::Init() 
{
	#ifdef _WIN32
		SavePath = "save/";
		CreateDirectory(SavePath.c_str(), NULL);
	#else
		SavePath = stringc(getenv("HOME")) + stringc("/.fonline/");
		mkdir(SavePath.c_str(), S_IRWXU | S_IXGRP | S_IRGRP | S_IXOTH | S_IROTH);
	#endif

	LastIPAddress = "127.0.0.1";
	LastAccountName = "";

	return 1;
}

// Destructor
void ConfigClass::Close() {

}

// Gets the save path to a file
void ConfigClass::GetSavePath(const stringc &TFile, stringc &TPath) 
{
	TPath = SavePath + stringc(TFile);
}

// Loads settings
bool ConfigClass::LoadSettings() 
{
	// Get filename
	stringc SaveFile;
	GetSavePath("settings.cfg", SaveFile);

	// Open file
	ifstream File;
	File.open(SaveFile.c_str(), ios::in);
	if(!File.is_open()) {
		File.clear();

		return SaveSettings();
	}
	File.width(32);

	// Get IP address
	char IPAddress[32];
	File >> IPAddress;

	// Get account name
	char AccountName[32];
	File >> AccountName;

	LastIPAddress = IPAddress;
	LastAccountName = AccountName;

	// Close
	File.clear();
	File.close();

	return true;
}

// Saves settings
bool ConfigClass::SaveSettings() 
{
	// Get filename
	stringc SaveFile;
	GetSavePath("settings.cfg", SaveFile);

	// Open file
	ofstream File;
	File.open(SaveFile.c_str(), ios::out);
	if(!File.is_open()) {
		File.clear();

		return false;
	}

	// Save settings
	File << LastIPAddress.c_str() << endl;
	if(LastAccountName == "")
		File << endl;
	else
		File << LastAccountName.c_str() << endl;

	// Close
	File.clear();
	File.close();

	return true;
}
